package demoMod.nanaki.powers;

import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.PowerStrings;
import com.megacrit.cardcrawl.powers.AbstractPower;
import demoMod.nanaki.NanakiMod;
import demoMod.nanaki.utils.GetWaitAction;
import demoMod.nanaki.utils.PowerRegionLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpiritualismPower extends AbstractPower {
    public static final String POWER_ID = NanakiMod.makeID("SpiritualismPower");
    private static final PowerStrings powerStrings;
    public static final String NAME;
    public static final String[] DESC;

    public SpiritualismPower(AbstractCreature owner, int amount) {
        this.name = NAME;
        this.ID = POWER_ID;
        this.owner = owner;
        this.amount = amount;
        this.updateDescription();
        PowerRegionLoader.load(this);
    }

    @Override
    public void updateDescription() {
        this.description = String.format(DESC[0], this.amount);
    }

    @Override
    public void atStartOfTurnPostDraw() {
        this.flash();
        addToBot(GetWaitAction.doAndWait(() -> {
            if (AbstractDungeon.player.hand.isEmpty()) {
                return;
            }
            Map<Integer, List<AbstractCard>> cardCostGroups = new HashMap<>();
            for (AbstractCard card : AbstractDungeon.player.hand.group) {
                if (!cardCostGroups.containsKey(card.costForTurn)) {
                    cardCostGroups.put(card.costForTurn, new ArrayList<>());
                }
                cardCostGroups.get(card.costForTurn).add(card);
            }
            List<Integer> costList = new ArrayList<>(cardCostGroups.keySet());
            costList.sort(Integer::compare);
            List<AbstractCard> cardsToReduceCost = cardCostGroups.get(costList.get(costList.size() - 1));
            AbstractCard card;
            if (cardsToReduceCost.size() > 1) {
                card = cardsToReduceCost.get(AbstractDungeon.cardRandomRng.random(cardsToReduceCost.size() - 1));
            } else {
                card = cardsToReduceCost.get(0);
            }
            card.setCostForTurn(card.costForTurn - 2);
            card.flash();
        }, 0.0F));
    }

    static {
        powerStrings = CardCrawlGame.languagePack.getPowerStrings(POWER_ID);
        NAME = powerStrings.NAME;
        DESC = powerStrings.DESCRIPTIONS;
    }
}
